package com.monas.client.export;

import java.io.IOException;
import java.io.OutputStream;
import java.util.LinkedList;

/**
 * Rendering file csv untuk kebutuhan record yang sangat banyak.
 * 
 * @author 'EkoWahyudi'
 * 
 */
public class CSVFile extends Renderer {

	/**
	 * Ekstensi file untuk csv.
	 */
	public static final String EXTENSION = ".csv";

	/**
	 * Pemisah antara field-field di baris.
	 */
	private String delimiter = null;

	/**
	 * Render tabel menjadi file csv.
	 * 
	 * @param delimiter
	 *            pemisah field
	 */
	public CSVFile(String delimiter) {
		this.delimiter = delimiter;
		records = new LinkedList<Object[]>();
	}

	@Override
	public void writeTo(OutputStream outputStream) throws IOException {
		/**
		 * Tulis header dulu.
		 */
		for (int i = 0; i < headers.length; i++) {
			if (i > 0) {
				outputStream.write(delimiter.getBytes());
			}
			outputStream.write(headers[i].getName().getBytes());
		}
		outputStream.write("\n".getBytes());

		/**
		 * Buat isi dari tabel.
		 */
		for (int i = 0; i < records.size(); i++) {
			Object[] fields = records.get(i);
			for (int j = 0; j < fields.length; j++) {
				if (j > 0) {
					outputStream.write(delimiter.getBytes());
				}

				if (fields[j] != null) {
					outputStream.write(fields[j].toString().getBytes());
				}
			}
			outputStream.write("\n".getBytes());
		}

	}

	@Override
	public void render() {
	}

}
